package com.MutiModule.websocket.controller;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.MutiModule.websocket.vo.CalcInput;
import com.MutiModule.websocket.vo.Result;

@Controller
public class WebSocketController {

	@MessageMapping("/add")
	@SendTo("/topic/showResult")
	public Result addNum(CalcInput input) throws Exception {
		Thread.sleep(2000);
		Result result = new Result(input.getNum1() + "+" + input.getNum2()
				+ "=" + (input.getNum1() + input.getNum2()));
		return result;
	}

	@RequestMapping("/start")
	public String start() {
		return "start";
	}
	
	
	//-----------------------服务端向客户端发送消息---------------------------------------------------------- begin
	private final MessageSendingOperations<String> messagingTemplate;

    @Autowired
    public WebSocketController(
        final MessageSendingOperations<String> messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }
    
    @RequestMapping("/send")
    @ResponseBody
	public void send() {
    	int num1 = new Random().nextInt(100);
    	int num2 = new Random().nextInt(100);
    	this.messagingTemplate.convertAndSend(
                "/topic/showResult", new Result(num1 + "+" + num2
        				+ "=" + (num1 + num2)));
    }
  //-----------------------服务端向客户端发送消息---------------------------------------------------------- end
}
